/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 12:01:09
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-24 14:56:35
 * @FilePath: \keep_motion_api\models\sport\sportRecord.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 运动记录模型
const sportRecordSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  sport_type: { 
    type: Schema.Types.ObjectId, 
    ref: 'SportType',
    required: true 
  },
  duration: Number,
  calories: Number,
  start_time: { type: Date, default: Date.now },
  end_time: Date,
  device: String,
  distance: Number
});
sportRecordSchema.statics.getSportRecords = async function (user_name, user_id, sport_type, sport_name, offset, limit) {
  try {
    const query = {};
    if(user_name){
      const { User } = require('../user');
      const parentQuery = {};
      const escapedUserName = escapeRegex(user_name);
      parentQuery.name = { $regex: escapedUserName, $options: 'i' };  
      const rows = await User.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const user_ids = rows.map(item => item._id);
      query.user_id = {$in: user_ids};
    }
    if(sport_name){
      const { SportType } = require('./');
      const parentQuery = {};
      const escapedSportName = escapeRegex(sport_name);
      parentQuery.name = { $regex: escapedSportName, $options: 'i' };  
      const rows = await SportType.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const sport_type_ids = rows.map(item => item._id);
      query.sport_type = {$in: sport_type_ids};
    }
    if(user_id){
      query.user_id = user_id;
    }
    if(sport_type){
      query.sport_type = sport_type;
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.aggregate([
      { $match: query },                   // 匹配查询条件
      { $lookup: {
        from: 'sporttypes',
        localField: 'sport_type',
        foreignField: '_id',
        as: 'sport_Info'
      }},
      { $lookup: {
        from: 'users',
        localField: 'user_id',
        foreignField: '_id',
        as: 'user_info'
      }},
      { $unwind: '$sport_Info' },
      { $unwind: '$user_info' },
      { $project: {
        _id: 1,
        user_id: 1,
        sport_type: 1,
        duration: 1,
        calories: 1,
        start_time: 1,
        end_time: 1,
        device: 1,
        distance: 1,
        sport_name: '$sport_Info.name',
        user_name: '$user_info.name'
      }},
      { $skip: Number(offset) },           // 分页跳过
      { $limit: Number(limit) },          // 分页限制
      { $sort: { start_time: -1 } }       // 按创建时间降序排序
    ]);
    return { rows, total };
  } catch (error) {
    throw new Error('获取运动记录失败');
  }
}
sportRecordSchema.statics.createSportRecords = async function (params) {
  try {
    const sportRecord = new this(params);
    return await sportRecord.save();
  } catch (error) {
    throw new Error('创建运动记录失败');
  }
}
sportRecordSchema.statics.updateSportRecords = async function (id, params) {
  try {
    const sportRecord = await this.findByIdAndUpdate(id, params, { new: true });
    if (!sportRecord) throw new Error('运动记录不存在');
    return sportRecord;
  } catch (error) {
    throw new Error('更新运动记录失败');
  }
}
sportRecordSchema.statics.deleteSportRecords = async function (id) {
  try {
    const sportRecord = await this.findByIdAndDelete(id);
    if (!sportRecord) throw new Error('运动记录不存在');
    return sportRecord;
  } catch (error) {
    throw new Error('删除运动记录失败');
  }
}
module.exports = mongoose.model('SportRecord', sportRecordSchema);
